<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\BizException;
use App\Http\Controllers\Controller;
use App\Model\HomeModule;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class HomeModuleController extends Controller
{
    public $agent;

    public function __construct()
    {
        $this->middleware(['admin']);
    }

    public function index(Request $request)
    {
        $params = $request->all();
        $model = HomeModule::where('status', '>', '-1');
        $list = $model->orderBy('order_num', 'desc')->orderBy('id', 'desc')->paginate(15);
        return view('admin.homeModule.index', [
            'list' => $list,
            'params' => $params,
        ]);
    }

    public function add(Request $request)
    {
        if ($request->getMethod() == 'POST') {
            try {
                $this->validate($request, [
                    'title' => 'required',
                ], [
                    'title.required' => '模块标题必填',
                ]);

                $params = $request->all();
                HomeModule::create($params);
                return response()->json(['status' => 1, 'info' => '保存成功']);
            } catch (ValidationException $e) {
                return response()->json(['status' => 0, 'info' => $e->validator->errors()->first()]);
            } catch (BizException $e) {
                return response()->json(['status' => 0, 'info' => $e->getMessage()]);
            }
        } else {
            return view('admin.homeModule.add');
        }
    }

    public function edit(Request $request)
    {
        if ($request->getMethod() == 'POST') {
            try {
                $this->validate($request, [
                    'title' => 'required',
                ], [
                    'title.required' => '模块标题必填',
                ]);

                $params = $request->all();
                $id = $params['id'];

                if (isset($params['id']))
                    unset($params['id']);
                HomeModule::where('id', $id)->update($params);
                return response()->json(['status' => 1, 'info' => '保存成功']);
            } catch (ValidationException $e) {
                return response()->json(['status' => 0, 'info' => $e->validator->errors()->first()]);
            } catch (BizException $e) {
                return response()->json(['status' => 0, 'info' => $e->getMessage()]);
            }
        } else {
            $row = HomeModule::find($request->input('id'));
            return view('admin.homeModule.edit', ['row' => $row]);
        }
    }

    public function del(Request $request)
    {
        HomeModule::where('id', $request->input('id'))->update(['status' => -1]);
        return response()->json(['status' => 1, 'info' => '删除成功']);
    }
}